import React, { useState, useEffect } from "react";
import { useHistory } from "react-router-dom";
import { Link } from "react-router-dom";
import { Form, Input, Button } from "antd";
import "./login.scss";
import "antd/dist/antd.css";
import { post } from "../manger/network";
import tokenManager from "../manger/tokenManager";

const FormItem = Form.Item;

export default function Login() {
  const [userName, setUserName] = useState("");
  const [password, setPassword] = useState("");
  const history = useHistory();
  return (
    <div className="loginView">
      <Form className="login-form">
        <FormItem>
          <Input
            placeholder="请输入用户名"
            onChange={(e) => setUserName(e.target.value)}
            maxLength={20}
          />
        </FormItem>
        <FormItem>
          <Input
            placeholder="请输入密码"
            onChange={(e) => setPassword(e.target.value)}
            maxLength={20}
            type="password"
          />
        </FormItem>
        <FormItem>
          <Button
            className="login-confirm"
            type="primary"
            onClick={() => {
              console.log("userName", userName);
              login(userName, password)
                .then((response) => {
                  if (response.code == 0) {
                    if (response.data && response.data.token) {
                      tokenManager.setToken(response.data.token);
                    }
                    history.push("/home");
                  }
                })
                .catch((err) => {
                  console.log(err);
                });
            }}
          >
            登录
          </Button>
        </FormItem>
      </Form>
    </div>
  );
}

async function login(userName, password) {
  return post("/login", {
    userName,
    password,
  });
}
